package cn.wolfcode.web.controller;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.UserUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    public static final ConcurrentHashMap<Long,Boolean> local_flag = new ConcurrentHashMap<>();


    @RequestMapping("/doSeckill")
    @RequireLogin
    public Result<String> doSeckill(int time , Long seckillId, HttpServletRequest request){
        //2对参数进行校验
        if (StringUtils.isEmpty(time + "") || StringUtils.isEmpty(seckillId + "")){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }

        Boolean is_loical_flag = local_flag.get(seckillId);
        if(is_loical_flag != null && is_loical_flag){
           throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //3判断他是否在活动时间内
        SeckillProductVo seckillProductVo = seckillProductService.find(time, seckillId);
        //4判断库存是否足够
        Integer count = seckillProductVo.getStockCount();
        if (count < 0){
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //5判断用户是否重复下单
           //获取用户信息
        String token = request.getHeader("token");
        UserInfo userInfo = UserUtil.getUser(redisTemplate, token);
        Boolean isFlag = redisTemplate.opsForSet().isMember(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time + ""), userInfo.getPhone() + ":" + seckillId);
        if (isFlag){
            throw  new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        }
        //利用redis控制人数
        Long stockCount = redisTemplate.opsForHash().increment(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + ""), seckillId+"", -1);
        if (stockCount < 0){
            //把本地标识设置成true
            local_flag.put(seckillId,true);
            throw  new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //把我们的数据封装成消息发送到MQ中
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setSeckillId(seckillId);
        orderMessage.setTime(time);
        orderMessage.setToken(token);
        orderMessage.setUserPhone(userInfo.getPhone());
        //利用MQ 去发送消息
        rocketMQTemplate.syncSend(MQConstant.ORDER_PEDDING_TOPIC,orderMessage);

        //6真正执行秒杀业务逻辑
         return Result.success("正在请购中请稍后......");
    }

    @RequestMapping("/find")
    @RequireLogin
    public Result<OrderInfo> find(String orderNo,HttpServletRequest request){
        //判断参数是否为空
        if (StringUtils.isEmpty(orderNo)){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //根据订单编号去查询订单消息
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if (orderInfo == null){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //登录的用户只看自己的信息
        String token = request.getHeader("token");
        UserInfo userInfo = UserUtil.getUser(redisTemplate, token);
        if (!userInfo.getPhone().equals(orderInfo.getUserId())){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        return Result.success(orderInfo);
    }

}
